package com.wyj.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class SocketChannelDemo {
    public static void main(String[] args) throws IOException {
        //1、创建客户端通道
        SocketChannel socketChannel = SocketChannel.open();
        //    2、绑定端口
        boolean connect = socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
        // socketChannel.bind(new InetSocketAddress("127.0.0.1",9999));
        //    3、写入数据
        socketChannel.write(ByteBuffer.wrap("这是客户端发送到消息".getBytes(StandardCharsets.UTF_8)));
        //    4、读取接收到的服务端消息
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(byteBuffer);
        System.out.println("客户端接收到消息：" + new String(byteBuffer.array(), 0, read, StandardCharsets.UTF_8));
        //    5、关闭连接
        socketChannel.close();


    }
}
